package com.imdroid.lite.activities;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.imdroid.lite.IMDroid;
import com.imdroid.lite.R;
import com.imdroid.lite.net.HttpHelper;
import com.imdroid.lite.process.ProcessFactory;
import com.imdroid.lite.process.UserProcess;

public class MainActivity extends BaseActivity {
	/**
	 * The TAG of the activity
	 */
	private static String TAG = "MainActivity";
	/**
	 * 进度条常量
	 */
	private ProgressBar mProgress;
	/**
	 * 中断下载变量
	 */
	private boolean interceptFlag = false;
	/**
	 * 下载对话框
	 */
	private Dialog alertDialog;
	/**
	 * 下载对话框
	 */
	private Dialog downloadDialog;
	/**
	 * 下载文件
	 */
	private String saveFileName = "IMDroid-Lite.apk";
	// 最后提示更新时间
	private long lastUpdateRemind = 0;

	// 消息常量
	private final static int MESSAGE_DOWN_PROGRESS = 0x501;
	private final static int MESSAGE_DOWN_DONE = 0x502;

	public static MainActivity instance;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
		setContentView(R.layout.main);
		Log.d(TAG, "onCreate...");
		// 取得控件
		// Button addr = (Button) findViewById(R.id.btn_addr);
		// Button loc = (Button) findViewById(R.id.btn_loc);

		// 设置控件状态
		// User currentUser = IMDroid.getUser();
		// boolean isLite = (currentUser.getType() == User.TYPE_DEVICE_LITE);
		// addr.setEnabled(isLite);
		// loc.setEnabled(isLite);
		// msgSetting.setEnabled(isLite);
		// bluetooth.setEnabled(isLite);

		// int drawable = isLite ? R.drawable.btn_home_selector
		// : R.drawable.btn_theme_gray;
		// addr.setBackgroundResource(drawable);
		// loc.setBackgroundResource(drawable);
		// msgSetting.setBackgroundResource(drawable);
		// bluetooth.setBackgroundResource(drawable);
		// 启动通知服务，连接服务器
		// startService(new Intent(this, NotificationService.class));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.carac.activities.BaseActivity#onResume()
	 */
	protected void onResume() {
		super.onResume();
		// 检查是否有新版本
		if ((new Date()).getTime() - lastUpdateRemind > 24 * 60 * 60 * 1000)
			(new CheckNewVersionTask()).execute(new Object());

		// 更新welcome text
		TextView tv = (TextView) this.findViewById(R.id.home_welcome_text);
		tv.setText(getWelcomeText());
		// if ((new Date()).getTime() - lastUpdateRemind > 24 * 60 * 60 * 1000)
		// messageHandler.sendEmptyMessage(MESSAGE_CHECK_VERSION);

		// Date today = new Date();
		// Date lastSyncDate = IMDroid.getContactLastSync();
		//
		// Log.d(TAG, "user type---" + IMDroid.getUser().getType());
		// 如果3天没有同步联系人
		// if (IMDroid.getUser().getType() == User.TYPE_DEVICE_LITE
		// && today.getTime() - lastSyncDate.getTime() > 3 * 24 * 60 * 1000) {
		// syncContacts();
		//
		// }
		
		TextView addr = ((TextView) findViewById(R.id.addr_text));
		TextView loc = ((TextView) findViewById(R.id.loc_text));
		if(IMDroid.getUser() != null && IMDroid.getUser().getType() == 2){
			addr.setTextColor(getResources().getColor(R.color.white));
			loc.setTextColor(getResources().getColor(R.color.white));
		} else {
			addr.setTextColor(getResources().getColor(R.color.gray));
			loc.setTextColor(getResources().getColor(R.color.gray));
		}
	}

	/**
	 * welcome text
	 * 
	 * @return the welcome text
	 */
	private String getWelcomeText() {
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		String welcomeText;
		if (hour < 6)
			welcomeText = this.getString(R.string.home_welcome_text_e);
		else if (hour < 12)
			welcomeText = this.getString(R.string.home_welcome_text_m);
		else if (hour < 14)
			welcomeText = this.getString(R.string.home_welcome_text_a);
		else if (hour < 18)
			welcomeText = this.getString(R.string.home_welcome_text_n);
		else
			welcomeText = this.getString(R.string.home_welcome_text_e);
		return welcomeText.replace("%1%", IMDroid.getUser().getNickname());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	public void onDestroy() {
		// 注销通知服务，连接服务器
		// Intent i = new Intent(Intent.ACTION_RUN);
		// i.setClass(this, NotificationService.class);
		// this.stopService(i);
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.lite.activities.BaseActivity#onKeyDown(int,
	 * android.view.KeyEvent)
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder buidler = new AlertDialog.Builder(this);
			buidler.setMessage(R.string.home_exit_confirm);

			buidler.setPositiveButton(R.string.home_confirm,
					new OnClickListener() {
						public void onClick(DialogInterface arg0, int arg1) {
							// ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).restartPackage(getPackageName());
							// System.exit(0);
							// exit();
							finish();
						}
					});
			buidler.setNegativeButton(R.string.home_cancel, null);

			buidler.show();
		}
		return super.onKeyDown(keyCode, event);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.imdroid.carac.activities.BaseActivity#processedMessage(android.os
	 * .Message)
	 */
	public void processedMessage(Message msg) throws Exception {
		super.processedMessage(msg);

		switch (msg.what) {
		case MESSAGE_DOWN_PROGRESS:
			int progress = (Integer) msg.obj;
			mProgress.setProgress(progress);
			break;
		case MESSAGE_DOWN_DONE:
			downloadDialog.dismiss();
			installApk();
			break;
		default:
			break;
		}
	}

	/**
	 * 组队
	 * 
	 * @param view
	 *            the button of team.
	 */
	public void team(View view) {
		startActivity(new Intent(this, TeamSelectActivity.class));
	}

	/**
	 * Exit the applicatoin.
	 */
	public void exit() {
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	/**
	 * 下发地址
	 * 
	 * @param view
	 *            the button of sending the address
	 */
	public void addr(View view) {

		if (IMDroid.getUser().getType() != 2) {
			AlertDialog.Builder buidler = new AlertDialog.Builder(this);
			buidler.setTitle(R.string.remind);
			buidler.setMessage(R.string.main_hint_client);

			buidler.setPositiveButton(this.getString(R.string.home_confirm),
					null);
			// new OnClickListener() {
			// public void onClick(DialogInterface arg0, int arg1) {
			// MainActivity.this.startActivity(new Intent(
			// MainActivity.this,
			// NavigatorPointSetting.class));
			// }
			// });
			buidler.show();
		} else {
			startActivity(new Intent(this, NavigatorPointSetting.class));
		}
	}

	/**
	 * 爱车位置
	 * 
	 * @param view
	 *            the button of the location
	 */
	public void loc(View view) {
		if (IMDroid.getUser().getType() != 2) {
			AlertDialog.Builder buidler = new AlertDialog.Builder(this);
			buidler.setTitle(R.string.remind);
			buidler.setMessage(R.string.main_hint_client);

			buidler.setPositiveButton(this.getString(R.string.home_confirm),
					null);
			// new OnClickListener() {
			// public void onClick(DialogInterface arg0, int arg1) {
			// MainActivity.this.startActivity(new Intent(
			// MainActivity.this,
			// CarLocationActivity.class));
			// }
			// });
			buidler.show();
		} else {
			startActivity(new Intent(this, CarLocationActivity.class));
		}
	}

	/**
	 * 信息设置
	 * 
	 * @param view
	 *            the button setting
	 */
	public void msgSetting(View view) {

		startActivity(new Intent(this, HomeRegisterActivity.class));
	}

	/**
	 * Show the check dialog
	 * 
	 * @throws Exception
	 */
	private void showCheckDialog() {
		// 从服务器上检查是否有新版本下载
		// if (hasNewVersion()) {
		lastUpdateRemind = (new Date()).getTime();
		AlertDialog.Builder builder = new Builder(this);

		builder.setTitle(R.string.home_version_title);
		builder.setMessage(R.string.home_version);

		builder.setPositiveButton("Ok", new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton("Cancel", new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
			}
		});
		alertDialog = builder.create();
		alertDialog.show();
	}

	/**
	 * Show the download dialog
	 */
	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(R.string.home_version_title);
		builder.setMessage(R.string.home_version_upgrade);

		final LayoutInflater inflater = LayoutInflater.from(this);
		View v = inflater.inflate(R.layout.home_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.home_progress);

		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();
		(new DownloadApkTask()).execute(mProgress);
		// downLoadThread = new Thread(mdownApkRunnable);
		// downLoadThread.start();
		// download();
	}

	/**
	 * Install the apk file
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(IMDroid.APP_FOLDER + "/" + saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		this.startActivity(i);
	}

	/**
	 * The async task to send the address
	 * 
	 */
	private class CheckNewVersionTask extends AsyncTask<Object, Void, Boolean> {
		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Boolean doInBackground(Object... params) {
			String clientVersion;
			try {
				clientVersion = IMDroid.getAppVersion();
				UserProcess process = (UserProcess) ProcessFactory
						.getProcess(UserProcess.class);
				String serverVersion = process.getLastVersion();
				return !serverVersion.startsWith(clientVersion);
			} catch (Exception e) {
				Log.d(TAG, "Error in Checking New version." + e.getMessage());
				return false;
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// 如果有版本更新
			if (result) {
				showCheckDialog();
			}
		}
	}

	private class DownloadApkTask extends
			AsyncTask<ProgressBar, Integer, Boolean> {
		/**
		 * The apk file url
		 */
		private String apkUrl = HttpHelper.ServerAddress
				+ "resource/client/IMDroid-Lite.apk";

		private int fileSize = 0;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		protected Boolean doInBackground(ProgressBar... params) {
			try {
				// 如果文件存在，则删除
				File apkFile = new File(IMDroid.APP_FOLDER + "/" + saveFileName);
				if (apkFile.exists())
					apkFile.delete();

				// 打开HTTP连接
				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				fileSize = conn.getContentLength();
				InputStream is = conn.getInputStream();
				FileOutputStream fos = new FileOutputStream(apkFile);

				int count = 0;
				byte buf[] = new byte[1024];
				do {
					int numread = is.read(buf);
					count += numread;

					if (numread <= 0) {
						return true;
					}
					fos.write(buf, 0, numread);
					this.publishProgress(count);

				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
				return !interceptFlag;
			} catch (Exception e) {
				return false;
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			// 下载完成通知安装
			if (result)
				messageHandler.sendEmptyMessage(MainActivity.MESSAGE_DOWN_DONE);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		protected void onProgressUpdate(Integer... values) {
			// 更新进度
			int precentage = (int) (((float) values[0] / fileSize) * 100);
			Log.d(TAG, "-->" + values[0] + "/" + fileSize + "/" + precentage);
			Message m = new Message();
			m.what = MainActivity.MESSAGE_DOWN_PROGRESS;
			m.obj = precentage;
			messageHandler.sendMessage(m);
		}

	}
	/**
	 * 同步联系人
	 */
	// private void syncContacts() {
	// new Thread() {
	//
	// /*
	// * (non-Javadoc)
	// *
	// * @see java.lang.Thread#run()
	// */
	// public void run() {
	// Log.d("TAG", "Start to sync....");
	// UserProcess p = (UserProcess) ProcessFactory
	// .getProcess(UserProcess.class);
	// try {
	// IMDroid.setContactLastSync(new Date());
	// p.synchronizeContact(IMDroid.getAppContext());
	// } catch (Exception e) {
	// Log.d("TAG", e.getMessage());
	// e.printStackTrace();
	//
	// }
	// }
	//
	// }.start();
	// }
}
